﻿using System.Net;
using System.Web.Script.Serialization;
using D3DSS.DataContract;
using D3DSS.IDomain;
using D3DSS.Model;
using D3DSS.Utility;
using System;
using D3DSS.IRepository;
using System.Collections.Generic;

namespace D3DSS.Domain
{
    /// <summary>
    /// 更新领域服务
    /// </summary>
    public class Update : IUpdate
    {
        /// <summary>
        /// 更新仓储接口
        /// </summary>
        protected IRepository<UpdateInfoModel> UpdateInfoRepository { get; set; }

        public Update(IRepository<UpdateInfoModel> updateInfoRepository)
        {
            UpdateInfoRepository = updateInfoRepository;
        }

        /// <summary>
        /// 判断是否需要更新
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Response<UpdateResponse> IsUpdate(UpdateRequest request)
        {
            var response = new Response<UpdateResponse>();
            response.Data = new UpdateResponse();
            response.IsSuccess = true;
            Version clientVersion = Version.Parse(request.Version);
            var updates = UpdateInfoRepository.All();
            var update = updates.Find(u =>
            {
                Version serverVersion = Version.Parse(u.Version);
                return serverVersion > clientVersion;
            });
            if (update != null)
            {
                response.Data.DownloadUrl = update.DownloadUrl;
                response.Data.UpdateNote = update.UpdateNote;
                response.Data.IsUpdate = true;
            }
            else
            {
                response.Data.IsUpdate = false;
            }
            return response;
        }
    }
}
